package io.forlove.framework.mudrock.rpc;

import io.forlove.framework.mudrock.config.Configs;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

@Log4j2
@Component
@Conditional(ConsumerCondition.class)
public class ClientServer {

    private Configs.ConsumerConfig config;

    @Autowired
    public void getClientConfig(Configs configs){
        this.config = configs.getConsumerConfig();
    }

    private Channel channel;

    @PostConstruct
    public void init() {

        try {
            NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();

            Bootstrap bootstrap = new Bootstrap().group(nioEventLoopGroup).channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 8, 1));
//                    ch.pipeline().addLast(new ClentRpcHandler());
                }
            });
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(config.getRemote(), config.getPort()));
            future.addListener(connectFuture -> {
                if (connectFuture.isSuccess()) {
                    log.info("connect to {}:{} success", config.getRemote(), config.getPort());
                    this.channel = future.channel();
                } else {
                    log.error("connect to {}:{} fail ", config.getRemote());
                    try {
                        future.get();
                    } catch (Exception e) {
                        log.error(e);
                    }
                }
            });
            future.channel().closeFuture().addListener(future12 -> {
                log.info("channal close");
                nioEventLoopGroup.shutdownGracefully();
            });

        }catch (Exception e){
            log.error("client server error");
            log.error(e);
        }
    }

    public void send(RpcQuest rpcMessage){
       this.channel.writeAndFlush(rpcMessage);
    }

}
class ConsumerCondition extends AnyNestedCondition {

    public ConsumerCondition() {
        super(ConfigurationPhase.PARSE_CONFIGURATION);
    }

    @ConditionalOnProperty(prefix = "mudrock",name = "mode", havingValue = "consumer")
    static class Value1Condition {
    }

    @ConditionalOnProperty(prefix= "mudrock",name="mode", havingValue = "both")
    static class Value2Condition {
    }
}


